package fr.inserm.u915.organifooyi.model;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class OrganiFooyiDao
 	{
	@PersistenceContext
	private EntityManager em;

	
	public void setEm(EntityManager em) {
		this.em = em;
		}
	
	public OrganiFooyiDao() {

	}
	
		
	public Prelevement getPrelevementById(long id)
		{
		return em.find(Prelevement.class, id);
		}
	
	
	public List<Prelevement> findPrelevementsByName(String term)
		{
		return this.em.createNamedQuery(
				"prelevementsFindByName"
				,Prelevement.class).
				setParameter("term", term).
				getResultList()
				;
		}
	
	public List<PostIt> getPostIts(String table,long id)
		{
		return this.em.createNamedQuery(
				"postitFindByTableAndId"
				,PostIt.class).
				setParameter("foreignTable", table).
				setParameter("foreignId", id).
				getResultList()
				;
		}

	
	
	public User getUserById(long id)
		{
		return em.find(User.class, id);
		}
	
	public User getUserByName(String login)
		{
		if(login==null || login.trim().isEmpty()) return null;
		try
			{
			return this.em.createNamedQuery(
					"userFindByLogin"
					,User.class).
					setParameter("login", login).
					getSingleResult();
			}
		catch(javax.persistence.NoResultException err)
			{
			System.err.println("Cannot get login for "+login);
			return null;
			}
		}

	//@Transactional
	public void persist(User user) {
		em.persist(user);
	}

	
	public void persist(Prelevement o)
		{
		em.persist(o);
		}
	
	public void persist(PostIt o)
		{
		em.persist(o);	
		}

	
	public void flush()
		{
		this.em.flush();
		}

	
	public List<Prelevement> getPrelevements()
		{
		return this.em.createNamedQuery(
				"prelevementsListAll"
				,Prelevement.class).getResultList();
		}
	
}
